﻿var _helper;
	
//#region 辅助函数
//获取模块
function m(){var m = $('script:last').attr('src');m = m.substr(0, m.lastIndexOf('/js/module.js') + 1);return m;}
//词典中，获取关键字对应的值
function l(m, k){return _helper.dict(m, k);}
//获取对象名称
function o(f){return f.toString().match(/^function (\w+)\(/)[1];}
//获取页面变量值
function v(p, n){return $('>section', p).data(n);}
//#endregion 辅助函数

function Helper()
{
	//私有变量
	var __templates = [];
	
	//初始化指定标签页面
	this.init = function(element, index, nav, reload)
	{
		//url
		var url;
		if (nav)
			url = nav;
		else
			url = ali.navTab(element, 'getUrl', index);
		
		//template
		var template = null;
		var instanceId = url.match(/\/\d+\//)[0];
		var instanceIdIndex = url.indexOf(instanceId);
		var templatePath = url.substr(instanceIdIndex + instanceId.length - 1);
		var pageIndex = templatePath.lastIndexOf('/page/');
		templatePath = templatePath.substr(0, pageIndex + 1);
		for (i = 0; i < __templates.length; i++)
		{
			if (__templates[i].path == templatePath)
				template = __templates[i];
		}
		
		//如果第一次使用该模板，则添加到缓存
		if (!template)
		{
			template = {path:templatePath,dict:null,init:null}
			__templates.push(template);
			
			//加载词典
			var dict = template.path + 'dictionary/' + $('html').attr('lang') + '.js';
			$.ajax(
			{
				url: dict,
				type: 'GET',
				dataType: 'json',
				async: false,
				success: function(data)
				{
					template.dict = data;
				}
			});
			
			//加载脚本
			var js = template.path + 'js/module.js';
			$('body').append('<script src="' + js + '">');
		}

		//获取页面名称
		var panel,page;
		if (nav)
		{
			panel = $('.frame1-left .ali-panel-body');
			page = 'nav';
		}
		else
		{
			panel = ali.navTab(element, 'getPanel', index);
			page = $('>section', panel).data('page');

			//清楚所有事件绑定
			if (!reload)
				panel.off();
		}

		template.init(instanceId.substr(1, instanceId.length - 2), page, panel, url, reload);
	};
	
	this.addInit = function(path, init)
	{
		for (var i = 0; i < __templates.length; i++)
		{
			if (__templates[i].path == path)
				__templates[i].init = init;
		}
	};
	
	this.dict = function(path, key)
	{
		for (var i in __templates)
		{
			if (__templates[i].path == path)
			{
				for (var name in __templates[i].dict)
				{
					if (key == name)
						return __templates[i].dict[name];
				}
			}
		}
		return key;
	};
	
	this.get = function(options)
	{
		return send($.extend(options, {type:'GET',silent:true}));
	};

	this.post = function(options)
	{
		return send($.extend(options, {type:'POST'}));
	};

	this.update = function (options)
	{
		var id = '';
		element = $(options.element);
		if (options.id)
			id = options.id;
		else if (element.parent().hasClass('toolbar1'))
			element.closest('.ali-navtab-panel').find('.ali-grid-body .ali-grid-row.ali-active').each(function(){id += id == '' ? $(this).data('id') : '|' + $(this).data('id');});
		else
			id = element.closest('tr').data('id');
			
		if (id == '')
		{
			ali.error(_lang_selection_empty);
			return;
		}

		options.params = 'ID=' + id;
		options.reload = true;
		options.operation = element.data('operation');
		if (options.operation == 'Delete')
			ali.confirm(_lang_confirm_delete, $.proxy(function(returnValue){if (returnValue)send(options);}, this));
		else
			send(options);
	};

	function send(options)
	{
		options = $.extend({data:{},lang:_lang,type:'POST',statusMessage:_lang_working,silent:false}, options);

		var url;
		if (options.url)
		{
			url = options.url;
		}
		else
		{
			url = _webPath + 'alicms.aspx?Lang=' + options.lang + '&Object=' + options.object + '&Operation=' + options.operation;
			if (options.instance)
				url += '&Instance=' + options.instance;
			if (options.params)
				url += '&' + options.params;
		}
		
		ali.working(options.statusMessage);

		var result = null;

		$.ajax(
		{
			url: url,
			data: options.data,
			type: options.type,
			async: false,
			error: function(jqXHR)
			{
				ali.error(_lang_operation_fail + '<br>' + unescape(jqXHR.responseText));
			},
			success: function(data)
			{
				if (!options.silent)
					ali.success(_lang_operation_success);

				if (options.reload && options.element)
				{
					var panel = $(options.element).closest('.ali-navtab-panel');
					var so = panel.find('.search1');
					if (so.length)
						so.submit();
				}
			
				if (options.callback)
					options.callback(data);

				result = data;
			}
		});
		
		return result;
	}

	this.isAllowedType = function(path, type)
	{
		if (!/^[A-Za-z]:\\/.test(path))
			return true;

		var ext = path.substr(path.lastIndexOf('.') + 1).toLowerCase();
		var types = type.toLowerCase().split('|');
		for (var i = 0; i < types.length; i++)
		{
			if (types[i] == ext)
				return true;
		}
		
		return false;
	};

	this.toAbsPanel = function(panel, path)
	{
		var index = panel.parent().children('.ali-navtab-panel').index(panel),
			base = ali.navTab('.ali-navtab', 'getUrl', index);

		return this.toAbsUrl(base, path);
	};
	
	this.toAbsUrl = function(base, path)
	{
		var index = base.indexOf('?');
		if (index == -1)
			index = base.lastIndexOf('/');
		else
			index = base.lastIndexOf('/', index);
		base = base.substr(0, index + 1);
		
		var a = document.createElement('a')
		a.href = base + path;
		
		return a.href.replace('http://' + (document.location.port == 80 ? document.domain : document.location.host), '');
	};
	
	this.resizeContentBlock = function(panels)
	{
		$(panels).each(function()
		{
			var content = $('.content', $(this));
			if (content.length)
			{
				var parent = content.parent(),
					maxHeight = parent.height();
				content.siblings(':visible').each(function()
				{
					var me = $(this);
					var position = me.css('position');
	
					if (position === 'absolute' || position === 'fixed')
						return;
	
					maxHeight -= me.outerHeight(true);
				});
				content.height(maxHeight);
			}
		});
	}

	//提交表单页面重新计算高度
	this.resizePostBlock = function(panels)
	{
		$(panels).each(function ()
		{
			var post = $('.post', $(this));
			if (post.length)
			{
				var parent = post.parent(),
					maxHeight = parent.height();
				post.siblings(':visible').each(function ()
				{
					var me = $(this);
					var position = me.css('position');

					if (position === 'absolute' || position === 'fixed')
						return;

					maxHeight -= me.outerHeight(true);
				});
				post.height(maxHeight);

				var h = maxHeight - $('>.post-footer', post).height();
				//if (h - 100 < $('>.post-body', post).height())
				$('>.post-body', post).height(h);
			}
		});
	};
	
	this.serialize = function(form)
	{
		//提前html编辑器内容填充到textarea上
		$('textarea.editor', form).each(function()
		{
			//this.value = CKEDITOR.instances[this.id].getData();
			this.value = UE.getEditor($(this).prev().attr('id')).getContent();
		});
		
		//上传组件如果需要上传，则不让序列化
		$('.ali-uploader', form).each(function()
		{
			if (ali.uploader(this, 'needUpload'))
				$(this).prev().prop('disabled', true);
		});
		
		//把只有bool类型的没有禁用的复选框禁用
		var checkboxes = [];
		$('[name!=""]:checkbox:enabled', form).each(function()
		{
			if ($(this).attr('value') == undefined && $('[name="' + this.name + '"]', form).length == 1)
				checkboxes.push($(this).prop('disabled', true));
		});
		
		//
		var data = $(form).serialize();
		
		//把前面禁用的复选框加到data里
		for (var i = 0; i < checkboxes.length; i++)
		{
			checkboxes[i].prop('disabled', false);
			data += '&' + checkboxes[i].attr('name') + '=' + checkboxes[i].prop('checked');
		}
		
		//上传组件取消禁用
		$('.ali-uploader', form).each(function()
		{
			$(this).prev().prop('disabled', false);
		});

		return data;
	};
		
	this.onDialogBeforeLoad = function(element, data)
	{
		data = data.match(/<section data-page="(.|\s)*?<\/section>/);
		if (!data) return;
		data = data[0];

		return data;
	};
	
	this.onDialogShow = function(element)
	{
		//设置标题
		ali.dialog(element, 'option', 'title', $('section', element).data('title'));
		
		//calendar
		ali.calendar($('[data-ali-widget=calendar]', element));
	
		//grid
		ali.grid($('[data-ali-widget=grid]', element));
		
		//combo
		ali.combo($('[data-ali-widget=combo]', element));
		
		//uploader
		ali.uploader($('.ali-uploader', element));

		//button
		ali.button($('.ali-button', element));

		//调整尺寸
		_helper.resizeContentBlock(element);
		_helper.resizePostBlock(element);
	};

	this.onPageIdCandidateChange = function ()
	{
		var form = this.form;
		var pageId = $('[data-name=PageID]', form);
		if (this.value == '')
		{
			pageId.val(this.value);
			return;
		}

		if (ali.util.ie)
		{
			pageId.focus();
			document.selection.createRange().text = this.value;
		}
		else
		{
			pageId.val(this.value);
		}
	};
	
	this.parsePlayer = function()
	{
		if (this.value != 'parse1' && this.value != 'parse2')
			return true;
		
		var params = '';
		if (this.value == 'parse2')
			params = '&FindSource=true';
	
		ali.working(_lang_working);
	
		var me = $(this);
		var input = me.prev();
		
		$.getJSON(_webPath + 'alicms.aspx?Mark=System&Object=Player&Operation=Parse&Url=' + encodeURIComponent(input.val()) + params, function(player)
		{
			if (player.id)
			{
				if (me.val() == 'parse2')
					me.val('');
				else
					me.val(player.id);
				input.val(player.url);
				
				if (me.data('aliWidget') == 'combo')
					ali.combo(me, 'refresh', me[0].selectedIndex);
			}
			else
			{
				me.val('');
				
				if (me.data('aliWidget') == 'combo')
					ali.combo(me, 'refresh', me[0].selectedIndex);
			}
	
			ali.working();
		});
	
		return false;
	};
	
	//将URL中的QueryString转换为对象数组
	this.queryToArray = function (url)
	{
		var result = [];

		var index = url.indexOf('?');
		if (index == -1)
			return result;

		var query = url.substr(index + 1),
			kvs = query.split('&');

		for (var i in kvs)
		{
			var kv = kvs[i].split('=');
			result.push({ name: kv[0], value: kv[1] });
		}

		return result;
	};

	//选择对话框。options:{element:必须,lang:可选,instance:必须,object:必须,operation:必须,folder:可选,callback:可选,type:必须，image（默认）|file}
	this.openSelectDialog = function (options)
	{
		if ($('script[src*=ueditor]').length == 0)
			$('body').append('<script src="' + _commonPath + 'ueditor/ueditor.config.js"></script><script src="' + _commonPath + 'ueditor/ueditor.all.min.js"></script>');

		var serverUrl = UEDITOR_CONFIG.UEDITOR_HOME_URL + 'net/controller.ashx?Lang=' + (options.lang ? options.lang : _lang) + '&Instance=' + options.instance + '&Object=' + options.object + '&Operation=' + options.operation + '&From=Page';
		if (options.root)
			serverUrl += '&Root=' + encodeURIComponent(options.root);
		if (options.folder)
			serverUrl += '&Folder=' + encodeURIComponent(options.folder);

		if ($('#select-dialog').length)
		{
			UE.getEditor('select-dialog').destroy();
			$('#select-dialog').remove();
		}

		$('body').append('<div id="select-dialog" style="display:none"></div>');
		var editor = UE.getEditor('select-dialog', { serverUrl: serverUrl });
		editor.ready(function ()
		{
			//隐藏编辑器
			editor.hide();

			if (options.type == 'file')
			{
				//删除事件绑定
				if (editor.__allListeners.beforeexeccommand)
					editor.__allListeners.beforeexeccommand.length = 0;

				//添加事件绑定
				editor.addListener('beforeExecCommand', function ()
				{
					if (arguments.length != 3 || arguments[1] != 'insertfile')
						return;

					if (options.callback)
						options.callback(arguments[2][1][0].url);
					else
						$(options.element).prevAll(':text').val(arguments[2][1][0].url);
				});

				//打开对话框
				editor.ui._dialogs.attachmentDialog.open();
			}
			else
			{
				//删除事件绑定
				if (editor.__allListeners.beforeinsertimage)
					editor.__allListeners.beforeinsertimage.length = 0;

				//添加事件绑定
				editor.addListener('beforeInsertImage', function (t, arg)
				{
					if (options.callback)
					{
						options.callback(arg[0].src);
					}
					else
					{
						$(options.element).prevAll(':text').val(arg[0].src);
						var a = $(options.element).next('a:has(img)');
						if (a.length)
							a.attr('href', arg[0].src).find('img').attr('src', arg[0].src);
					}
				});

				//打开对话框
				editor.ui._dialogs.insertimageDialog.open();
			}
		});

		return false;
	};
}

function Index()
{
	var __hashByCode = true,
		__fromHashChange = false,
		__silent = false;
	
	this.init = function()
	{
		//实例化调度器
		_helper = new Helper();

		//ajax提交时，显示工作中
		$(document).ajaxStart(function(){if (__silent) return;ali.working(_lang_working);}).ajaxStop(function(){ali.working();});
		
		//设置侧栏默认宽度
		$('.frame1-left').data('width', 200);

		//设置菜单	
		ali.tabs('.menu', {event:'click', onActivate:onMenuActivate});

		//调整框架宽度
		onResize();

		//修改密码
		$('.header1-right #password').click(onPasswordClick);
		$('#password-dialog').submit(onPasswordSubmit);
	
		//中栏设置为可拖放
		$('.frame1-mid').draggable(
		{
			axis: 'x',
			helper: 'clone',
			drag: function(e, ui)
			{
				var l = ui.offset.left;
				$('.frame1-right').width($('.frame1').width() - l - $('.frame1-mid').width());
				$('.frame1-left').width(l).data('width', l);
			}
		});
	
		//初始化界面部件
		ali.panel('.frame1-left>.ali-panel', {dir:'h',heightStyle:'fill',onBeforeToggle:onLeftNavExpand,onToggle:onResize});
		ali.accordion('.ali-accordion', {heightStyle:'fill'});
		ali.combo('[data-ali-widget=combo]');
		ali.tree('.ali-tree');
		ali.navTab('.ali-navtab', {heightStyle:'fill',onBeforeLoad:onNavTabBeforeLoad,onLoad:onNavTabLoad,onActivate:onNavTabActivate});
		ali.tabs('.frame1 .ali-tabs');
	
		//绑定窗口大小变化事件
		$(window).bind('resize', onResize);

		//实现前进和后退
		$(window).bind('hashchange', function (e)
		{
			var hashUrl = document.location.hash.substr(1);
			if (!__hashByCode)
			{
				__fromHashChange = true;
				ali.navTab('.ali-navtab', 'open', {url:hashUrl});
			}

			__hashByCode = false;

			//侧栏跟着当前页面调整
			var id = hashUrl.substr(_channelPath.length);
			id = id.substr(0, id.indexOf('/'));
			var menu = $('.menu [data-id="' + id + '"]');
			if (menu.length)
			{
				menu.click();
			}
		});

		//维吾尔文、哈萨克文和柯尔克孜文输入法安装
		$('body').on('keydown', '.UYGFont,.KZAFont,KGAFont', OnEdit).on('keypress', '.UYGFont,.KZAFont,KGAFont', OnEdit);
		
		//上传组件初始化
		ali.uploader(null, {url:_webPath + 'alicms.aspx'});
		
		//主栏上的通用处理
		$('.frame1-right')
						.on('submit', '.search1', onSearch)
						.on('submit', '.search2', onDialogSearch)
						.on('change', '.path1 dd [data-ali-widget=combo]', onLangChange)/*页面内容语言*/
						.on('change', '.search1 select', function(){onSearch.call(this.form);onSearchSelectChange.call(this);})
						.on('click', '.search1 :checkbox', function(){onSearch.call(this.form);})
						.on('change', '.ali-navtab-panel>section .content .pagination1 [name=PageSize]', function(){var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, $(this).closest('.pagination1').data('pageNumber'), this.value);})
						.on('click', '.ali-navtab-panel>section .content .pagination1 a', function(){var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, $(this).attr('href'));return false;})
						.on('click', '.ali-navtab-panel>section>.content .pagination1 .go button', function(){var p = $(this).prev();if (!p.val().match(/\d+/) || parseInt(p.val()) >= parseInt($(this).closest('.pagination1').data('pageCount'))){ali.error(_lang_page_number_incorrect, function(){p.select();});return;}var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, p.val());})
						.on('click', '.ali-dialog-body .pagination1 a', function(){var form = $(this).closest('.ali-dialog-body').find('.search2');onDialogSearch.call(form, $(this).attr('href'));return false;})
						.on('click', '.toolbar1 .select-all', function(){var grid = $(this).parent().nextAll('.content').find('>.ali-grid');$('.ali-grid-row', grid).removeClass('ali-active').addClass('ali-active');})
						.on('click', '.toolbar1 .select-reverse', function(){var grid = $(this).parent().nextAll('.content').find('>.ali-grid');$('.ali-grid-row', grid).toggleClass('ali-active');});
		
		//全局内容语言
		$('#content-lang').change(function(){ali.util.cookie('DefaultContentLanguage', this.value, 10*360*24*60, '/');});
		
		//如果hash里带网址的话，直接打开该网址。否则，打开第一个菜单的子菜单
		if (location.hash != '')
		{
			//侧栏跟着当前页面调整
			var url = location.hash.substr(1);
			var id = url.substr(_channelPath.length);
			id = id.substr(0, id.indexOf('/'));
			var menu = $('.menu [data-id="' + id + '"]');
			if (menu.length)
			{
				menu.click();
			}

			//
			ali.navTab('.ali-navtab', 'open', {title:'new tab',url:url});
		}
		else
		{
			$('.menu a:first').click();//自动点击第一个菜单
		}
		$('.menu').css('visibility', 'visible');
	};
	
	function onLangChange()
	{
		var panel = $(this).closest('.ali-navtab-panel');
		var index = panel.parent().children('.ali-navtab-panel').index(panel);
		var navTab = panel.closest('.ali-navtab');
		var url = ali.navTab(navTab, 'getUrl', index);
		
		url = url.replace(/Lang=\w+&?/, '');
		index = url.indexOf('?');
		if (index != -1)
			url = url.substr(0, index + 1) + 'Lang=' + this.value + '&' + url.substr(index + 1);
		else
			url += '?Lang=' + this.value;
		
		ali.navTab(navTab, 'reload', null, {url:url});

		__hashByCode = true;
		location.hash = url;
	}
	
	function onDialogSearch()
	{
		var pageNumber = 1;
		if (arguments.length > 0 && typeof(arguments[0]) != 'object')
			pageNumber = arguments[0];

		var param = 'Page=' + pageNumber,
			element = $(this).closest('.ali-dialog-body').children(),
			search2 = $('.search2', element),
			requires = $('.ali-input-required', search2);
		
		for (var i = 0; i < requires.length; i++)
		{
			if ($.trim(requires[i].value) == '')
			{
				ali.error(_lang_required, $.proxy(function(){requires[i].select();}, this));
				return false;
			}
		}

		$('select,:text,:checkbox', search2).each(function()
		{
			param += '&' + this.name + '=' + (this.type == 'checkbox' ? this.checked : encodeURIComponent(this.value));
		});
		
		var url = ali.dialog(element, 'option', 'url');
		var index = url.indexOf('?');
		if (index != -1)
			url = url.substr(0, index);

		if ($(this).attr('action') == '')
			url += '?' + param;
		else
			url += $(this).attr('action') + '&' + param;

		ali.dialog(element, 'reload', {url:url, onBeforeLoad:function(element, data)
		{
			var m = data.match(/(<div class="content"[^>]*>)(.|\s)*?(<\/ul>|<\/table>)\s*<\/div>/);
			data = m[0].substr(m[1].length, m[0].length - m[1].length - 6);

			var content = $('.content', element).html(data);
			
			//grid
			ali.grid($('[data-ali-widget=grid]', content));

			//button
			ali.button($('.ali-button', element));

			return null;
		}});

		return false;
	}
	
	function onSearch()
	{
		var pagination = $(this).parent().find('.pagination1');

		var pageNumber = 1;
		if (arguments.length > 0 && typeof (arguments[0]) != 'object')
			pageNumber = arguments[0];
		else if (pagination.length)
			pageNumber = $('.active', pagination).text();

		var pageSize = 20;
		if (arguments.length > 1)
			pageSize = arguments[1];
		else if (pagination.length)
			pageSize = $('[name=PageSize]', pagination).val();

		data = 'Page=' + pageNumber + '&PageSize=' + pageSize;
		
		$('select,:text,:checkbox', this).each(function()
		{
			data += '&' + this.name + '=' + (this.type == 'checkbox' ? this.checked : encodeURIComponent(this.value));
		});
		
		var form = $(this);
		var panel = form.closest('.ali-navtab-panel');
		var index = panel.parent().children('.ali-navtab-panel').index(panel);
		var navTab = panel.closest('.ali-navtab');
		var url = ali.navTab(navTab, 'getUrl', index);
		index = url.indexOf('?');
		if (index != -1)
			url = url.substr(0, index);

		if ($(this).attr('action') == '')
			url += '?' + data;
		else
			url += $(this).attr('action') + '&' + data;

		ali.navTab(navTab, 'reload', null, {url:url, onBeforeLoad:function(element, index, data)
		{
			data = data.match(/<div class="(\w+\s)?content">(.|\s)*?(<\/ul>|<\/table>)\s*<\/div>/);
			if (!data)
				return null;

			data = data[0];
			var start = data.indexOf('>') + 1;
			data = data.substr(start, data.length - start - 6);

			//把相对路径转换为绝对路径
			data = toAbsData(data, element, index);
			
			var content = form.nextAll('.content');
			content.html(data);
			
			//grid
			ali.grid($('[data-ali-widget=grid]', content));
			
			//combo
			ali.combo($('[data-ali-widget=combo]', content));
			
			//button
			ali.button($('.ali-button', content));

			//调整post尺寸
			if (content.hasClass('post'))
				_helper.resizePostBlock(content.parent());

			__hashByCode = true;
			location.hash = url;

			//重载初始化
			_helper.init(element, index, false, true);

			return null;
		}});
		
		return false;
	}
	
	function onSearchSelectChange()
	{
		var toolbar = $(this.form).nextAll('.toolbar1');
		if (this.name == 'IsRecycled')
		{
			if (this.value == 'true')
			{
				$('.recycle', toolbar).hide();
				$('.recover', toolbar).show();
				$('.delete', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.recycle', toolbar).show();
				$('.recover', toolbar).hide();
				$('.delete', toolbar).hide();
			}
			else
			{
				$('.recycle', toolbar).hide();
				$('.recover', toolbar).hide();
				$('.delete', toolbar).hide();
			}
		}
		else if (this.name == 'IsRecommended')
		{
			if (this.value == 'true')
			{
				$('.recommend', toolbar).hide();
				$('.unrecommend', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.recommend', toolbar).show();
				$('.unrecommend', toolbar).hide();
			}
			else
			{
				$('.recommend', toolbar).hide();
				$('.unrecommend', toolbar).hide();
			}
		}
		else if (this.name == 'IsHeld')
		{
			if (this.value == 'true')
			{
				$('.hold', toolbar).hide();
				$('.unhold', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.hold', toolbar).show();
				$('.unhold', toolbar).hide();
			}
			else
			{
				$('.hold', toolbar).hide();
				$('.unhold', toolbar).hide();
			}
		}
		else if (this.name == 'IsChecked')
		{
			if (this.value == 'true')
			{
				$('.check', toolbar).hide();
				$('.uncheck', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.check', toolbar).show();
				$('.uncheck', toolbar).hide();
			}
			else
			{
				$('.check', toolbar).hide();
				$('.uncheck', toolbar).hide();
			}
		}
		else if (this.name == 'IsDisplay')
		{
			if (this.value == 'true')
			{
				$('.display', toolbar).hide();
				$('.undisplay', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.display', toolbar).show();
				$('.undisplay', toolbar).hide();
			}
			else
			{
				$('.display', toolbar).hide();
				$('.undisplay', toolbar).hide();
			}
		}
	}
	
	function loadNav(parentID, url)
	{
		if (!url || url == '')
			url = 'nav.aspx';

		__silent = true;
		$.get(url + '?ParentID=' + parentID, function(data)
		{
			var $p = $('.frame1-left .ali-panel-body');
			var nav = data.match(/<section data-page="(.|\s)*?<\/section>/);
			$p.html(nav);
			$('section', $p).height($p.height());
			ali.tree($('.ali-tree', $p));
			ali.accordion($('.ali-accordion', $p));
			
			//通过html()写入内容的时候，href的地址在ie8以下版本中变成绝对地址，改回站内绝对地址
			if (ali.util.ie6 || ali.util.ie7)
			{
				$('section [href]', $p).each(function()
				{
					var host = 'http://' + document.location.host;
					var href = $(this).attr('href');
					if (href.indexOf(host) == 0)
						$(this).attr('href', href.substr(host.length));
				});
			}
			
			if (url != 'nav.aspx')
				_helper.init(null, null, url);
		});
		__silent = false;
	}
	
	function onMenuActivate(e, ui)
	{
		//修改侧栏标题
		$('.frame1-left .ali-panel-header:first b').text(ui.newTab.text());
		
		var a = $('>a', ui.newTab);
		var url = a.attr('href');
		if (url && url != '')
			ali.navTab('.ali-navtab', 'open', {url:url});
		
		//导入侧栏导航
		loadNav(a.data('id'), a.data('nav'));
		
		return false;
	}
	
	function onLeftNavExpand(ui, type)
	{
		if (type == 'collapse')
		{
			$('.frame1-mid').draggable('disable').css('cursor', 'default');
			return;
		}
		
		$('.frame1-mid').draggable('enable').css('cursor', 'col-resize');
	
		var l = $('.frame1-left').data('width');
		$('.frame1-right').width($('.frame1').width() - l - $('.frame1-mid').width());
		$('.frame1-left').width(l);
	}
	
	function onResize(ui, type)
	{
		//frame1宽度
		var w = $('html').width() - parseInt($('.frame1').css('padding-left').replace('px', '')) - parseInt($('.frame1').css('padding-right').replace('px', ''));
		$('.frame1').width(w);
	
		//frame1-left宽度
		var l;
		if (type == 'collapse')
			l = $('.frame1-left .ali-panel').outerWidth();
		else
			l = $('.frame1-left').data('width');
		$('.frame1-left').width(l);
		
		//frame1-right宽度
		$('.frame1-right').width(w - l - $('.frame1-mid').width());
		
		//frame1-left,frame1-mid和frame1-right高度
		var h = $('html').height() - $('.header1').height() - $('.menu').height() - parseInt($('.frame1').css('margin-top').replace('px', '')) - parseInt($('.frame1').css('margin-bottom').replace('px', ''));
		$('.frame1-left,.frame1-mid,.frame1-right').height(h);
		
		//触发resize事件
		$('.frame1-left>.ali-panel,.frame1-right>.ali-navtab').trigger('ali-resize');
		$('.frame1-left .ali-panel-body>section,.frame1-right>.ali-navtab>.ali-navtab-panel>section').each(function(){$(this).height($(this).parent().height())});
		_helper.resizePostBlock('.frame1-right>.ali-navtab>.ali-navtab-panel');
		_helper.resizeContentBlock('.frame1-right>.ali-navtab>.ali-navtab-panel');
		$('.frame1-right [data-ali-widget=grid]').trigger('ali-resize');
		$('.ali-accordion').trigger('ali-resize');
	}
	
	function toAbsData(data, element, index)
	{
		urls = [];
		var re = /href="([^"]*?)"\s+target="ali-navtab"/g,
			v;
		while ((v = re.exec(data)) != null)
		{
			if (v[1].match(/^(\/|http)/))
				continue;

			urls.push({start:v.index + 6,length:v[1].length});
		}
		
		var base = ali.navTab(element, 'getUrl', index);
		//base = base.substr(0, base.lastIndexOf('/') + 1);
		for (var i = urls.length -1; i >= 0; i--)
		{
			var s = urls[i].start,
				l = urls[i].length;

			data = data.substr(0, s) + _helper.toAbsUrl(base, data.substr(s, l)) + data.substr(s + l);
		}
		
		return data;
	}
	
	//navTab加载url之前调用
	function onNavTabBeforeLoad(element, index, data)
	{
		data = data.match(/<section data-page="(.|\s)*?<\/section>/);
		if (!data) return;
		data = data[0];

		//把相对路径转换为绝对路径
		data = toAbsData(data, element, index);

		return data;
	}
	
	//navTab加载url之后调用
	function onNavTabLoad(element, index)
	{
		var $p = ali.navTab(element, 'getPanel', index);
		
		//
		if (!__fromHashChange)
			__hashByCode = true;

		//
		if (v($p, 'lang') != undefined)
			_lang = v($p, 'lang');

		//
		$('section', $p).height($p.height());
		ali.navTab(element, 'setTitle', index, $('section', $p).data('title'));
		
		//子导航
		ali.tabs($('.sub-nav', $p));
		
		//提交表单（添加，编辑）
		_helper.resizePostBlock($p);
		
		//列表页面
		_helper.resizeContentBlock($p);
		
		//处理搜索表单状态
		var search = $('.search1', $p);
		if (search.length)
		{
			$.each(_helper.queryToArray(ali.navTab(element, 'getUrl', index)), function()
			{
				var element = $('[name="' + this.name + '"]', search);
				if (!element.length)
					return true;
	
				if ((element[0].tagName == 'INPUT' && element[0].type == 'text') || element[0].tagName == 'SELECT')
					element.val(decodeURIComponent(this.value));
				
				if (element[0].tagName == 'INPUT' && element[0].type == 'checkbox')
					element[0].checked = this.value.toLowerCase() == 'true' ? true : false;
			});
		}

		//accordion
		ali.accordion($('.ali-accordion', $p));
		
		//button
		ali.button($('.ali-button', $p));
		
		//calendar
		ali.calendar($('[data-ali-widget=calendar]', $p));
		
		//menu
		ali.menu($('.ali-menu', $p));
		
		//navTab
		ali.navTab($('.ali-navtab', $p), {target:'ali-navtab-test'});
		
		//tabs
		ali.tabs($('.ali-tabs', $p));
		
		//tree
		ali.tree($('.ali-tree', $p));
		
		//grid
		ali.grid($('[data-ali-widget=grid]', $p));
		
		//combo
		ali.combo($('[data-ali-widget=combo]', $p));
		
		//uploader
		ali.uploader($('.ali-uploader', $p));
		
		//panel
		ali.panel($('.ali-panel', $p));
		
		//html editor
		var editors = $('.editor,.editor-basic', $p);
		if (editors.length)
		{
			//#region ckeditor
			/*
			if ($('script[src*=ckeditor]').length == 0)
				$('body').append('<script src="' + _commonPath + 'ckeditor/ckeditor.js"></script>');
			
			editors.each(function()
			{
				this.id = ali.util.formatDate(new Date(), 'SSS');
				var config = {};
				if (typeof($(this).data('toolbar')) != 'undefined')
					config.toolbar = $(this).data('toolbar');

				if ($(this).data('lang') == 'UYG')
					config.language = 'ug';
				else
					config.language = 'zh-cn';

				if (typeof($(this).data('browseUrl')) != 'undefined')
				{
					config.filebrowserBrowseUrl = $(this).data('browseUrl');
					config.filebrowserImageBrowseUrl = $(this).data('browseUrl') + '&Type=Editor&ListByPicture=true';
				}
		
				config.contentLang = $(this).data('contentLang');
				if (config.contentLang == 'UYG' || config.contentLang == 'KZA' || config.contentLang == 'KGA')
				{
					config.contentsLangDirection = 'rtl';
					config.bodyClass = 'ckeditor-body-uyg';
				}
		
				if (typeof($(this).data('width')) != 'undefined')
					config.width = $(this).data('width');
				
				if (typeof($(this).data('height')) != 'undefined')
					config.height = $(this).data('height');
		
				if (typeof($(this).data('extraConfig')) != 'undefined')
					$.extend(config, eval('(' + $(this).data('extraConfig') + ')'));

				CKEDITOR.replace(this.id, config);
			});
			*/
			//#endregion
			
			//#region ueditor 
			if ($('script[src*=ueditor]').length == 0)
				$('body').append('<script src="' + _commonPath + 'ueditor/ueditor.config.js"></script><script src="' + _commonPath + 'ueditor/ueditor.all.min.js"></script>');
			
			editors.each(function()
			{
				var me = $(this);

				//设置id
				this.id = ali.util.formatDate(new Date(), 'SSS') + parseInt(Math.random() * 1000);

				//参数
				var param = {serverUrl:UEDITOR_CONFIG.UEDITOR_HOME_URL + 'net/controller.ashx?Lang=' + _lang + '&Instance=' + me.data('instance') + '&Object=' + (me.data('object') ? me.data('object') : 'InstanceConfig') + '&Operation=' + (me.data('operation') ? me.data('operation') : 'EditorUpload') + '&From=Editor',initialFrameWidth:me.parent().width() * 0.96};
				
				//如果是维哈柯文，则设置css
				if (_lang == 'UYG' || _lang == 'KZA' || _lang == 'KGA')
				{
					param.iframeCssUrl = UEDITOR_CONFIG.UEDITOR_HOME_URL + 'themes/iframeUYG.css';
				}
				
				//创建
				UE.getEditor(this.id, param).ready(function()
				{
					//维哈柯文输入
					if (_lang == 'UYG' || _lang == 'KZA' || _lang == 'KGA')
					{
						var $body = $(this.body);
						$body.attr('lang', _lang);
						$body.unbind('keydown').on('keydown', OnEdit);
						$body.unbind('keypress').on('keypress', OnEdit);
					}
				});
			});
			//#endregion
		}
		
		//处理toolbar状态
		$('.search1 select', $p).each(onSearchSelectChange);

		//添加和编辑页面里，guid复选框
		$('[data-operation=CheckGuid]').click(function ()
		{
			if (this.checked)
				$(this).parent().next().removeClass('ali-disabled').prop('disabled', false).focus();
			else
				$(this).parent().next().addClass('ali-disabled').prop('disabled', true);
		});
		
		//处理js
		_helper.init(element, index);
	}
	
	function onNavTabActivate()
	{
		__hashByCode = true;
	}

	//修改密码的对话框弹出
	function onPasswordClick()
	{
		ali.dialog('#password-dialog', {resizable:false});

		return false;
	}

	//把修改密码的表单提交
	function onPasswordSubmit()
	{
		var data = '';
		if (this.Name.value != $(this.Name).data('old'))
			data = 'Name=' + encodeURIComponent(this.Name.value);
		if (this.Password.value != '')
		{
			if (data != '')
				data += '&';
			data += 'Password=' + encodeURIComponent(this.Password.value);
		}

		if (data != '')
		{
			var id = _helper.post({ instance: 0, object: 'Admin', operation: 'GetInnerIDFromGuid', params: 'ID=' + ali.util.cookie('UserID'), silent: true });
			_helper.post({ instance: 0, object: 'Admin', operation: 'Modify', data: data, params: 'ID=' + id });
			$(this.Name).data('old', this.Name.value);
		}
		else
		{
			ali.success(_lang_operation_success);
		}
		
		return false;
	}
}

function Login()
{
	this.login = function()
	{
		if ($.trim(this.Name.value) == '' || $(this).data('tip') == this.Name.value)
		{
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
		
		if ($.trim(this.Password.value) == '')
		{
			ali.error(_lang_password_empty, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
		
		if (this.CheckCode != null && $.trim(this.CheckCode.value) == '')
		{
			ali.error(_lang_check_code_empty, $.proxy(function(){this.CheckCode.select();}, this));
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&Password=' + encodeURIComponent(this.Password.value);
		if (this.CheckCode != null)
			data += '&CheckCode=' + encodeURIComponent(this.CheckCode.value);
		if ($('#remember')[0].checked)
			data += "&Minutes=" + (60*24*365);
	
		var form = this;
		$(':submit', form).prop('disabled', true);
		
		ali.working(_lang_working);
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=Admin&Operation=Login',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_login_fail);
				$('#check-code-image').attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());
				ali.working();
				$(':submit', form).prop('disabled', false);
			},
			success: function()
			{
				window.location = window.location.href.replace('login', 'index');
			}
		});
		return false;
	};
	
	this.check = function()
	{
		if (ali.util.cookie('UserID') != '' && ali.util.cookie('Namespace') != 'AliCMS.SystemModule')
		{
			if (_loginPath == '')
			{
				$('#user-name').text(ali.util.cookie('UserName'));
				$('.login-right .ali-panel-body>div,.login-right form table').toggle();
			}
			else
			{
				$.ajax(
				{
					url: _loginPath,
					data: data,
					type: 'POST',
					success: function(userRoles)
					{
						if (_adminRole == '')
						{
							$('#user-name').text(ali.util.cookie('UserName'));
							$('.login-right .ali-panel-body>div,.login-right form table').toggle();
						}
						else
						{
							var hasRight = false;
							userRoles = userRoles.split('|');
							for (var i = 0; i < userRoles.length; i++)
							{
								if (userRoles[i].indexOf(_adminRole) != -1)
								{
									hasRight = true;
									break;
								}
							}
							
							if (hasRight)
							{
								$('#user-name').text(ali.util.cookie('UserName'));
								$('.login-right .ali-panel-body>div,.login-right form table').toggle();
							}
						}
					}
				});
			}
		}
	};
}

(function()
{
	if (_page == 'index')
	{
		var index = new Index();
		index.init();
	}
	else if (_page == 'login')
	{
		//界面元素
		ali.panel('.ali-panel', {heightStyle:'fill'});
		ali.button('.ali-button');
		
		//输入框焦点事件
		$('form [name=Name]').data('tip', $('form [name=Name]').val()).focus(function()
		{
			var me = $(this);
			if (me.data('tip') == me.val())
			{
				me.val('');
				me.toggleClass('tip');
			}
		}).blur(function()
		{
			var me = $(this);
			if (me.val() == '')
			{
				me.val(me.data('tip'));
				me.toggleClass('tip');
			}
		});
		
		//验证码
		$('#check-code-image').click(function(){$(this).attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());});
		
		//登录表单提交事件
		var login = new Login();
		$('form').submit(login.login);
		login.check();
	}
})();